package com.store.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.hyphenate.EMCallBack;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.LocationApplication;
import com.store.app.MainActivity;
import com.store.app.R;
import com.store.app.database.Database;
import com.store.app.database.DatabaseMethod;
import com.store.app.http.Stores;
import com.store.app.hyphenate.HyphenateHelper;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.push.PushUtils;
import com.store.app.utils.SettingData;
import com.store.app.utils.Utils;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Hashtable;

/**
 * 设置页面
 */
public class SetActivity extends BaseActivity implements View.OnClickListener, IOnHttpListener {

    private TextView tvTitle;   //标题栏--标题

    private ImageView erWeiMa;//显示二维码
    private LinearLayout ll_helper;//我的客服条目
    private LinearLayout ll_guide;//隐藏-暂时未用
    private LinearLayout ll_bind_taobao;//淘宝会员名条目
    private TextView tv_taobao_name;//淘宝会员名
    private LinearLayout ll_advice;//意见反馈条目
    private LinearLayout llAboutUs;//关于我们条目
    private TextView tvVersion;//隐藏-暂时未用

    private TextView quit;//退出登录

    private DatabaseMethod method;
    private Database database;

    SharedPreferences preferences;
    private NetRequest netRequest;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_set);
        initView();
        if (Stores.stores_name != null)
            ((TextView) findViewById(R.id.tv_name)).setText(Stores.stores_name);

        netRequest = new NetRequest(this);
        ll_advice = (LinearLayout) findViewById(R.id.ll_advice);
        ll_advice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(SetActivity.this, "017");
                Intent intent = new Intent(SetActivity.this, AdviceActivity.class);
                startActivity(intent);
            }
        });
		//透明状态栏
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        llAboutUs = (LinearLayout) findViewById(R.id.ll_about_us);
        llAboutUs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(SetActivity.this, "016");
                Intent intent = new Intent(SetActivity.this, AboutUsActivity.class);
                startActivity(intent);
            }
        });

        ll_guide = (LinearLayout) findViewById(R.id.ll_guide);
        ll_guide.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SetActivity.this, GuideShoppingActivity.class);
                startActivity(intent);

            }
        });
        tvVersion = (TextView) findViewById(R.id.tv_version);
        tvVersion.setText("V " + Utils.getVersion());

        database = new Database(this);
        method = new DatabaseMethod(database);
        ExitApplication.getInstance().addActivity(this);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        tvTitle.setText("设置");
        findViewById(R.id.public_ll_return).setOnClickListener(this);
        quit = (TextView) findViewById(R.id.quit);
        quit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(SetActivity.this);
                builder.
                        setMessage("确定退出登录？")
                        .setNegativeButton("取消", null);

                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        logout();
                        PushUtils.setAlias(SetActivity.this, "", null);
                        PushUtils.setTags(SetActivity.this, null, null);
                        LocationApplication.getData().clear();
                        method.clearFeedTable();
                        netRequest.requestLogout(1);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putString(MainActivity.PREF_APP_TOKEN, "").commit();
                        editor.putString(MainActivity.PREF_SECURITY_CODE, "").commit();
                        editor.putString(MainActivity.PREF_USER_TOKEN, "").commit();
                        editor.putString(MainActivity.PREF_USER_SECURITY_CODE, "").commit();
                        editor.putString(MainActivity.PREF_MEMBER_ID, "").commit();
                        editor.putString("member_id", "").commit();
                        editor.putString("area_id", "").commit();
                        editor.putString("stores_name", "").commit();
                        editor.putString("store_desc", "").commit();
                        editor.putString("contact_person", "").commit();
                        editor.putString("stores_type_key", "").commit();
                        editor.putString("business_type_key", "").commit();
                        editor.putString("contact_tel", "").commit();
                        editor.putString("address", "").commit();
                        editor.putString("neighbor_pic_path", "").commit();
                        editor.putString("longitude", "").commit();
                        editor.putString("latitude", "").commit();
                        editor.putString("im_user_id", "").commit();
                        Intent intent = new Intent();
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setClass(SetActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
                builder.show();
            }
        });

        erWeiMa = (ImageView) findViewById(R.id.iv_erweima);
        if (MainActivity.member_id != null)
            createQRImage(MainActivity.member_id);

        initData();
    }


    private void initView() {
        ll_helper = (LinearLayout) findViewById(R.id.ll_helper);
        ll_helper.setOnClickListener(this);
        ll_bind_taobao = (LinearLayout) findViewById(R.id.ll_bind_taobao);
        ll_bind_taobao.setOnClickListener(this);
        tv_taobao_name = (TextView) findViewById(R.id.tv_taobao_name);
    }

    private void initData() {
        //查询SP文件，看是否存有淘宝会员名，如果有，则直接获取；否则，请求网络获取
        String account_id = preferences.getString("account_id", "notQuery");
        if(!"notQuery".equals(account_id)){//键存在
            String account_no = preferences.getString("account_no", "");
            tv_taobao_name.setText(account_no);
        }else{//键不存在
            //登陆时未来得及查询，应再次查询
            if(!TextUtils.isEmpty(MainActivity.member_id)){
                netRequest.requestQueryTaoBao(2,MainActivity.member_id, SettingData.STORES);
            }
        }
    }

    public void logout() {

        HyphenateHelper.getInstance().logout(false, new EMCallBack() {

            @Override
            public void onSuccess() {
                Log.v("zyl", "退出环信成功");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.v("zyl", "退出环信失败：" + message);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.public_ll_return:
                finish();
                break;
            case R.id.ll_helper:
                Intent intent2 = new Intent(SetActivity.this, ContactHelperActivity.class);
                startActivity(intent2);
                break;
            case R.id.ll_bind_taobao:
                //判断是否有绑定淘宝会员名，如果没有，则跳到绑定页面，如果有，则跳到修改页面。
                String account_no = preferences.getString("account_no", "");//此时键account_no一定存在
                if(TextUtils.isEmpty(account_no)){
                    //未绑定淘宝账号
                    enterBindTaoBaoAccountActivity(getClass().getSimpleName());
                }else {
                    //已绑定淘宝账号
                    enterEditTaoBaoAccountActivity(account_no);
                }
                break;
        }
    }

    private static final int REQUEST_TAO_BAO_NAME = 100;
    /**
     * 进入绑定淘宝会员名界面
     */
    private void enterBindTaoBaoAccountActivity(String data) {
        Intent intent = new Intent(this, BindTaoBaoAccountActivity.class);
        intent.putExtra("startActivity",data);
        startActivityForResult(intent,REQUEST_TAO_BAO_NAME);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == REQUEST_TAO_BAO_NAME){
            if(resultCode == Activity.RESULT_OK){
                String account_no = data.getStringExtra("account_no");
                tv_taobao_name.setText(account_no);
            }
        }
    }

    /**
     * 进入编辑淘宝会员名界面
     */
    private void enterEditTaoBaoAccountActivity(String data) {
        Intent intent = new Intent(SetActivity.this, EditTaoBaoAccountActivity.class);
        intent.putExtra("account_no",data);
        startActivity(intent);
    }


    @Override
    public void onAfinalFail() {
        showToast("请检查本地网络！");
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            Log.v("zyl", "退出接口成功：" + result);
        }else if(requestId == 2){
            Log.d("xgp", "设置 querySuccess:" + result);
            try {
                //解析服务器返回的用户绑定的淘宝账户信息
                JSONObject jsonObject = new JSONObject(result);
                JSONArray taoBaojsonArray = jsonObject.getJSONArray("list");
                SharedPreferences.Editor editor = preferences.edit();
                if(taoBaojsonArray.length() == 0){//未绑定
                    editor.putString("account_id","").apply();
                    editor.putString("account_no","").apply();
                    //未绑定，跳转到绑定淘宝会员界面
                    tv_taobao_name.setText("");
                    enterBindTaoBaoAccountActivity(getClass().getSimpleName());
                }else{//已绑定
                    JSONObject taoBaojsonObject = taoBaojsonArray.getJSONObject(0);
                    String account_id = taoBaojsonObject.getString("account_id");
                    String account_no = taoBaojsonObject.getString("account_no");
                    Log.d("xgp", "account_id:" + account_id);
                    Log.d("xgp", "account_no:" + account_no);
                    //将用户绑定的淘宝账户信息存储到SP文件中
                    editor.putString("account_id",account_id).apply();
                    editor.putString("account_no",account_no).apply();
                    //已绑定，跳转到编辑淘宝会员界面
                    tv_taobao_name.setText(account_no);
                    enterEditTaoBaoAccountActivity(account_no);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        if (requestId == 1) {
            Log.v("zyl", "退出接口失败：" + msg);
        }
    }

    private int QR_WIDTH = 1200, QR_HEIGHT = 1200;

    // 要转换的地址或字符串,可以是中文
    public void createQRImage(String url) {
        try {

            Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            // 图像数据转换，使用了矩阵转换
            BitMatrix bitMatrix = new QRCodeWriter().encode(url,
                    BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
            int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
            // 下面这里按照二维码的算法，逐个生成二维码的图片，
            // 两个for循环是图片横列扫描的结果
            for (int y = 0; y < QR_HEIGHT; y++) {
                for (int x = 0; x < QR_WIDTH; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * QR_WIDTH + x] = 0xff000000;
                    } else {
                        pixels[y * QR_WIDTH + x] = 0xffffffff;
                    }
                }
            }
            // 生成二维码图片的格式，使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT,
                    Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
            // 显示到一个ImageView上面
            erWeiMa.setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}